package com.example.springboot.service.admin.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springboot.mapper.TagMapper;
import com.example.springboot.model.entity.Tag;
import com.example.springboot.model.form.PageUtil;
import com.example.springboot.model.form.Result;
import com.example.springboot.model.req.admin.TagReq;
import com.example.springboot.model.vo.TagVO;
import com.example.springboot.service.admin.TagService;
import com.example.springboot.utils.CopyUtil;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author zf
 * @标签表
 * @since 2021-03-25
 */
@Service
public class TagServiceImpl extends ServiceImpl<TagMapper, Tag> implements TagService {

    @Override
    public Result getPage(TagReq req) {
        IPage<Tag> ipage = page(req.toPage(), new LambdaQueryWrapper<Tag>()
                .eq(Objects.nonNull(req.getIsCommend()), Tag::getIsCommend, req.getIsCommend())
                .eq(Tag::getInvalid, 0)
                .orderByDesc(Tag::getCreateTime));

        Page<Tag> page = PageUtil.toPage(ipage);
        return Result.buildSuccess(PageUtil.convert(page, e -> {
            TagVO tagVO = CopyUtil.copyObject(e, TagVO.class);
            return tagVO;
        }));
    }

    @Override
    public Result addInfo(TagReq req) {
        //主表复制元素
        Tag tag = CopyUtil.copyObject(req, Tag.class);
        boolean flag;
        if (req.getId() != null) {
            flag = updateById(tag);
        } else {
            flag = save(tag);
        }
        if (flag) {
            return Result.buildSuccess();
        }
        return Result.buildFail();
    }


    @Override
    public Result deleteInfos(String ids) {
        if (update(new UpdateWrapper<Tag>().lambda()
                .set(Tag::getInvalid, 1)
                .inSql(Tag::getId, ids)
        )) {
            return Result.buildSuccess();
        }
        return Result.buildFail();
    }

}
